package cn.yshujia.repository;

import cn.yshujia.domain.dto.PageDTO;
import cn.yshujia.domain.entity.Develop;
import cn.yshujia.domain.vo.PageVO;
import cn.yshujia.mapper.DevelopMapper;
import cn.yshujia.utils.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @author YShuJia
 * @create 2025/3/16
 * @description DevelopRepository
 */


@Repository
public class DevelopRepository {
	
	@Resource
	RedisTemplate<String, Develop> redis;
	
	
	@Resource
	DevelopMapper mapper;
	
	
	private static final String VO = "develop:";
	
	private static final Duration VO_DURATION = Duration.ofDays(3L);
	
	public PageVO<Develop> pageByBranch (PageDTO dto){
		
		Map<String, Object> map = dto.getParam();
		if (ObjectUtils.isEmpty(map) || null == map.get("branch")) {
			return new PageVO<>();
		}
		
		String branch = map.get("branch").toString();
		
		long start = (long) (dto.getCurrent() - 1) * dto.getSize();
		
		List<Develop> list = redis.opsForList().range(VO + branch, start, start + dto.getSize() - 1);
		
		if (!ObjectUtils.isEmpty(list)) {
			return PageUtils.getPage(dto, list, redis.opsForList().size(VO + branch));
		}
		
		list = mapper.selectList(new LambdaQueryWrapper<Develop>()
				.eq(Develop::getBranch, branch)
				.orderByDesc(Develop::getTime));
		
		if (!ObjectUtils.isEmpty(list)) {
			redis.opsForList().rightPushAll(VO + branch, list);
			redis.expire(VO + branch, VO_DURATION);
			list = redis.opsForList().range(VO + branch, start, start + dto.getSize() - 1);
		}
		
		return PageUtils.getPage(dto, list, redis.opsForList().size(VO + branch));
	}
	
	@Async ("Task")
	public void del(String branch) {
		redis.delete(VO + branch);
	}
}
